package com.usian.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.pojo.Employee;
import com.usian.pojo.Result;
import com.usian.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
//登录第一种方式
//    @RequestMapping("/login")
//    public Result login(@RequestBody Employee employee ,HttpSession session){
//        Employee employee1 = employeeService.login(employee);
//        if (employee1!=null){
//            session.setAttribute("userInfo",employee1);
//            return Result.success(employee1);
//        }else {
//            return Result.error("登陆失败");
//        }
//    }
    //第二种方式登录
    @PostMapping("/login")
    public Result login(@RequestBody  Employee employee, HttpSession session){
        //1. 调用service的登录方法，返回一个R对象
        Result<Employee> result = employeeService.login(employee);

        //2. 判断是否登录成功，登录成功需要在session中做一个登录成功标记
        if(result.getCode()==1){
            session.setAttribute("employee",result.getData().getId());
        }
        //3. 返回给前端
        return result;

    }
    @PostMapping("logout")
    public Result logout(HttpSession session){
        session.invalidate();
        return Result.success("退出成功");
    }
    @PostMapping
    public Result save(@RequestBody Employee employee,HttpSession session){
        Long empid= (Long) session.getAttribute("employee");
        employee.setCreateUser(empid);
        employee.setUpdateUser(empid);
        employeeService.save(employee);
        return Result.success("添加成功");
    }
    @GetMapping("page")
    public Result page(@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "3")Integer pageSize,String name){
        Page<Employee> page1=employeeService.page(page,pageSize,name);
        return Result.success(page1);
    }
    @PutMapping
    public Result updateStatus(@RequestBody Employee employee,HttpSession session){
        Long empid= (Long) session.getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empid);
        employeeService.updateStatus(employee);
        return Result.success("修改状态成功");
    }
    @GetMapping("{id}")
    public Result findByid(@PathVariable Long id){
        Employee employee=employeeService.findByid(id);
        return Result.success(employee);
    }
}
